using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Collections.Specialized;

public partial class manager_members_AddEditUser : CMSManagementPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void odsMember_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        Page.Validate();
        if (!Page.IsValid)
            return;


        e.Cancel = true;
        TextBox txtPassword = (TextBox)fvUser.FindControl("txtInsertPassword");
        TextBox txtEmail = (TextBox)fvUser.FindControl("txtInsertEmail");
        Literal litUsername = (Literal)fvUser.FindControl("litInsertUsername");
        TextBox txtFirstname = (TextBox)fvUser.FindControl("txtInsertFirstname");
        TextBox txtSurname = (TextBox)fvUser.FindControl("txtInsertSurname");
        DropDownList ddlCustomer = (DropDownList)fvUser.FindControl("ddlInsertCustomer");
        DropDownList ddlWebsite = (DropDownList)fvUser.FindControl("ddlInsertWebsite");

        MembershipCreateStatus status;

        MembershipUser newUser = Membership.CreateUser(litUsername.Text,
            txtPassword.Text,
            txtEmail.Text, "Favorite Colour", "Blue", true, out status);

        if (status == MembershipCreateStatus.Success)
        {
            ProfileBase newProfile = ProfileBase.Create(litUsername.Text);
            newProfile.SetPropertyValue("Firstname", txtFirstname.Text);
            newProfile.SetPropertyValue("Surname", txtSurname.Text);
            newProfile.SetPropertyValue("CustomerID", int.Parse(ddlCustomer.SelectedValue));
            newProfile.SetPropertyValue("WebsiteID", int.Parse(ddlWebsite.SelectedValue));
            newProfile.Save();

            // add user to selected role
            DropDownList ddlRole = (DropDownList)fvUser.FindControl("ddlInsertRole");
            string role = ddlRole.SelectedValue;
            Roles.AddUserToRole(litUsername.Text, role);

            ShowSystemFeedback("The user account has been created.");

        }
        else 
        {
            string feedback = "";
            switch (status)
            {
                case MembershipCreateStatus.DuplicateEmail:
                    feedback = "A user already exists with that email address."; break;
                case MembershipCreateStatus.DuplicateUserName:
                    feedback = "A user already exists with that user name."; break;
                case MembershipCreateStatus.InvalidEmail:
                    feedback = "The email address provided is not valid."; break;
                case MembershipCreateStatus.InvalidPassword:
                    feedback = "The password must be at least " + Membership.Provider.MinRequiredPasswordLength.ToString() + " characters long."; break;
                case MembershipCreateStatus.InvalidUserName:
                    feedback = "The User Name provided is invalid. Please only use alpha-numeric characters."; break;
                case MembershipCreateStatus.UserRejected:
                    feedback = "The user has been rejected."; break;
                default:
                    feedback = status.ToString(); break;

            }
            feedback += "<br/>Could not create user.";
            ShowSystemFeedback(feedback);
        }

        fvUser.ChangeMode(FormViewMode.ReadOnly);
        odsMember.SelectParameters["usernameToFind"].DefaultValue = litUsername.Text;
        DataBind();

    }

    /// <summary>
    /// Calculate a username based on their personal data
    /// </summary>
    /// <param name="groupidentifier">An identifier which is the same for all users belonging to the same logical group e.g: customer, website, etc</param>
    /// <param name="firstname">The first name of the user</param>
    /// <param name="surname">The surname of the user</param>
    private string calculateUsername(string groupidentifier, string firstname, string surname)
    {
        int i = 1;

        string username = System.Text.RegularExpressions.Regex.Replace(groupidentifier + "." + firstname.Substring(0,1) + surname, "[^A-Za-z0-9.]", "").ToLower();
        MembershipUser checkExists = Membership.GetUser(username);

        // if the username exists then append the next available number to the end of the username
        string incrUsername = String.Empty;

        while (checkExists != null)
        {
            incrUsername = username + (i++).ToString();
            checkExists = Membership.GetUser(incrUsername);
        }
        if (incrUsername != String.Empty)
            username = incrUsername;

        return username;
    }


    protected void fvUser_Init(object sender, EventArgs e)
    {
        if (Request.QueryString["username"] == null)
            fvUser.ChangeMode(FormViewMode.Insert) ;
    }
    protected void txtSurname_TextChanged(object sender, EventArgs e)
    {

        TextBox txtFirstname = (TextBox)fvUser.FindControl("txtInsertFirstname");
        TextBox txtSurname = (TextBox)fvUser.FindControl("txtInsertSurname");
        Literal litUsername = (Literal)fvUser.FindControl("litInsertUsername");

        if (txtFirstname.Text == "" || txtSurname.Text == "")
            return;

        DropDownList ddlCustomer = (DropDownList)fvUser.FindControl("ddlInsertCustomer");

        if (ddlCustomer.SelectedItem == null)
            return;

        litUsername.Text = calculateUsername(ddlCustomer.SelectedItem.Text, txtFirstname.Text, txtSurname.Text);
    }

    protected void fvUser_DataBound(object sender, EventArgs e)
    {
        if (fvUser.CurrentMode == FormViewMode.ReadOnly)
        {
            Literal litRole = (Literal)fvUser.FindControl("litViewRole");
            if (litRole != null)
            {
                string[] roles = Roles.GetRolesForUser(litRole.Text);
                litRole.Text = "";
                foreach (string role in roles)
                {
                    if (litRole.Text.Length > 0)
                        litRole.Text += ", ";
                    litRole.Text += role;
                }
            }
        }
    }

    protected void ddlInsertCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
